<template>
    <div class="custom-container">
        <div class="monitor-box">
            <div class="console-box">
                <!--        <div class="console-panel" contenteditable="true"></div>-->
                <div class="console-panel" ref="consolePanel">
                    <div class="message-box" v-for="(item, index) in messageList" :key="index">
                        <div class="message-item">
                            <span class="message-time">
                                [{{ item.ts }}]
                                <span v-if="item.type === 1" style="color: #fff">[send]</span>
                                <span v-else>[recv]</span>
                            </span>
                            <span>{{ item.content }}</span>
                        </div>
                    </div>
                </div>
            </div>
        </div>
        <div class="control-box">
            <div class="tab-container">
                <el-tabs v-model="activeName" type="card" @tab-click="handleClick">
                    <el-tab-pane label="DTU操作" name="page1"></el-tab-pane>
                    <el-tab-pane label="DTU设置" name="page2"></el-tab-pane>
                    <el-tab-pane label="显示设置" name="page3"></el-tab-pane>
                </el-tabs>
            </div>
            <!-- <div class="form-row">
                <div style="width: 0;flex: 1;">
                    <el-input type="text" v-model="query.data" size="mini"></el-input>
                </div>
                <div style="width: 100px;flex-shrink: 0;text-align: center">
                    <el-button type="info" size="mini" @click="sendData" style="margin-left: 15px">发送</el-button>
                </div>
            </div> -->
            <div class="btn-box">
                <div class="btn-bg">
                    <div class="form-row">
                        <div class="row-label" title="">WS状态</div>
                        <div class="row-value">
                            <span v-if="info.ws_connect_status === '连接成功'"
                                style="color: #00cc00;font-weight: bold;">连接成功</span>
                            <span v-else style="font-weight: bold;">{{ info.ws_connect_status }}</span>
                        </div>
                    </div>
                    <div class="form-row">
                        <div class="row-label" title="">API状态</div>
                        <div class="row-value">
                            <span v-if="info.api_connect_status === '连接成功'"
                                style="color: #00cc00;font-weight: bold;">连接成功</span>
                            <span v-else style="font-weight: bold;">{{ info.api_connect_status }}</span>
                        </div>
                    </div>
                    <div class="form-row">
                        <div class="row-label" title="">dtuid</div>
                        <div class="row-value">
                            <el-select v-model="dtu_info.dtu_number" placeholder="" size="mini" style="max-width: 128px"
                                filterable>
                                <el-option v-for="(item) in client_list" :key="item" :label="item"
                                    :value="item"></el-option>
                            </el-select>
                            <el-button type="info" size="mini" style="max-width: 100px"
                                @click="udp_client_list">检测</el-button>
                        </div>
                    </div>
                </div>


                <div class="page-content" v-show="activeName === 'page1'">
                    <div class="btn-bg">
                        <div class="form-row">
                            <div class="row-label" title="">时间</div>
                            <div class="row-value">
                                <el-date-picker type="datetime" value-format="YYYY-MM-DD HH:mm:ss"
                                    v-model="dtu_info.data_time" placeholder="校时时间" size="mini"
                                    style="max-width: 180px"></el-date-picker>
                                <el-button type="info" size="mini" style="max-width: 100px"
                                    @click="dtu_syn_time('data_time')">校时命令</el-button>
                                <el-button type="info" size="mini" style="max-width: 100px"
                                    @click="dtu_syn_time('sys_time')">系统校时</el-button>
                            </div>
                        </div>
                    </div>
                    <div class="btn-bg" style="padding: 1px 15px 15px;">

                        <el-button type="info" size="mini" style="max-width: 100px" @click="dtu_get_data">主动查询</el-button>
                        <el-button type="info" size="mini" style="max-width: 100px" @click="dtu_set_resend">设置补发功能</el-button>
                        <el-button type="info" size="mini" style="max-width: 100px" @click="dtu_cancel_resend">取消补发功能</el-button>
                        <el-button type="info" size="mini" style="max-width: 100px" @click="dtu_clear_resend_data">清除补发数据</el-button>
                        <el-button type="info" size="mini" style="max-width: 100px" @click="dtu_clear_outage_data">清除断电记录</el-button>
                        <el-button type="info" size="mini" style="max-width: 120px" @click="rtu_get_info">查询RTU的参数</el-button>
                        <el-button type="info" size="mini" style="max-width: 120px" @click="reset_rtu">中心复位RTU</el-button>
                    </div>
                </div>
                <div class="page-content page2" v-show="activeName === 'page2'">
                    <div class="btn-bg left" style="flex-direction: column;">
                        <div class="form-row">
                            <div class="row-label" title="">ip</div>
                            <div class="row-value">
                                <el-input type="text" v-model="dtu_info.ip" size="mini" style="max-width: 180px"></el-input>
                            </div>
                        </div>
                        <div class="form-row">
                            <div class="row-label" title="">port</div>
                            <div class="row-value">
                                <el-input type="text" v-model="dtu_info.port" size="mini" style="max-width: 180px"></el-input>
                            </div>
                        </div>
                        <div class="form-row">
                            <div class="row-label" title="">dtu编号</div>
                            <div class="row-value">
                                <el-input type="text" v-model="dtu_info.dtu_number_new" size="mini" style="max-width: 180px"></el-input>
                            </div>
                        </div>
                        <div class="form-row">
                            <div class="row-label" title="">心跳包</div>
                            <div class="row-value">
                                <el-input type="text" v-model="dtu_info.heartbeat" size="mini" style="max-width: 180px" placeholder="*10s"></el-input>
                            </div>
                        </div>
                        <div class="form-row">
                            <div class="row-label" title="">DNS</div>
                            <div class="row-value">
                                <el-input type="text" v-model="dtu_info.dns" size="mini" style="max-width: 180px" placeholder="NULL"></el-input>
                            </div>
                        </div>
                    </div>
                    <div class="right" style="padding: 1px 15px 15px;">
                        <el-button type="info" size="mini" style="max-width: 150px" @click="dtu_get_setting" :disabled="true">DTU参数查询(开发中)</el-button>
                        <el-button type="info" size="mini" style="max-width: 150px" @click="dtu_set_setting('DNS')" :disabled="true">DNS参数设置(开发中)</el-button>
                        <el-button type="info" size="mini" style="max-width: 150px" @click="dtu_set_setting('')" :disabled="true">DTU参数设置(开发中)</el-button>
                        <!-- <el-button type="info" size="mini" style="max-width: 100px" @click="reset_dtu">DTU远程复位</el-button> -->
                    </div>
                </div>
                <div class="page-content" v-show="activeName === 'page3'">
                    <div class="btn-bg">
                        <div class="form-row">
                            <div class="row-label" title="">原始数据</div>
                            <div class="row-value">
                                <el-switch v-model="query.t0_show" size="mini"></el-switch>
                            </div>
                        </div>
                        <div class="form-row">
                            <div class="row-label" title="">异常数据</div>
                            <div class="row-value">
                                <el-switch v-model="query.t1_show" size="mini"></el-switch>
                            </div>
                        </div>
                        <div class="form-row">
                            <div class="row-label" title="">心跳包</div>
                            <div class="row-value">
                                <el-switch v-model="query.t2_show" size="mini"></el-switch>
                            </div>
                        </div>
                        <div class="form-row">
                            <div class="row-label" title="">整点上传</div>
                            <div class="row-value">
                                <el-switch v-model="query.t3_show" size="mini"></el-switch>
                            </div>
                        </div>
                        <div class="form-row">
                            <div class="row-label" title="">断电记录</div>
                            <div class="row-value">
                                <el-switch v-model="query.t4_show" size="mini"></el-switch>
                            </div>
                        </div>
                        <div class="form-row">
                            <div class="row-label" title="">自动滚动</div>
                            <div class="row-value">
                                <el-switch v-model="query.auto_scroll" size="mini"></el-switch>
                            </div>
                        </div>
                        <div class="form-row">
                            <div class="row-label" title=""></div>
                            <div class="row-value">
                                <el-button size="mini" style="max-width: 100px" @click="clearScreen">清屏</el-button>
                            </div>
                        </div>
                    </div>
                </div>

            </div>

        </div>
    </div>
</template>
<script>
const { ipcRenderer } = require('electron');
import { defineComponent } from "vue";
export default defineComponent({ name: 'dashboard' })
</script>
<script setup>
import { ref, onUnmounted, onDeactivated, onMounted, reactive, nextTick } from "vue";
import Methods from "../utils/Methods";
import request from "../utils/request";
import { ElMessage } from 'element-plus';
let socket;
let reconnectInterval = 1000; // 初始重连时间间隔，单位毫秒
let maxReconnectAttempts = 1000; // 最大重连次数
let reconnectAttempts = 0; // 当前重连次数
let reconnecting = false; // 标志是否正在尝试重连
let loginStatus = false

const activeName = ref('page1')
const handleClick = (tab, event) => {
    // console.log(tab, event)
}

const query = reactive({
    data: "",
    t0_show: false, // 0.原始数据
    t1_show: false, // 1.异常数据
    t2_show: false, // 2.心跳包
    t3_show: true, // 3.整点上传
    t4_show: true, // 4.断电记录
    t5_show: true, // 5.指令数据
    auto_scroll: true,
})

const info = reactive({
    ws_url: "",
    api_url: "",
    udp_port: "",
    ws_connect_status: "未连接",
    api_connect_status: "未连接",
})

const dtu_info = reactive({
    dtu_number: "",
    data_time: "",
    type: "",
    ip: "",
    port: "",
    dtu_number_new: "",
    heartbeat: "",
    dns: "NULL",
})

const loading = ref(false)

const dtu_syn_time = (type) => {
    if (!dtu_info.dtu_number) {
        ElMessage.warning("请选择dtu设备")
        return
    }
    if (type === "data_time" && !dtu_info.data_time) {
        ElMessage.warning("请设置校时时间")
        return
    }
    if (loading.value === true) {
        return
    }
    arrayPush({ content: "DTU校时 " + dtu_info.dtu_number, ts: 0, type: 1, data_type: 0 })
    loading.value = true
    let url = info.api_url + '/api/dtu_syn_time?dtu_number=' + dtu_info.dtu_number + '&data_time=' + dtu_info.data_time + '&type=' + type
    request.get(url).then(res => {
        loading.value = false
        if (res.code === 0) {
            console.log("dtu_syn_time", res);
        } else {
            ElMessage.error(res.message)
        }
    }).catch(err => {
        console.log(err);
        loading.value = false
    })
}
const dtu_get_data = () => {
    if (!dtu_info.dtu_number) {
        ElMessage.warning("请选择dtu设备")
        return
    }
    if (loading.value === true) {
        return
    }
    arrayPush({ content: "主动查询 " + dtu_info.dtu_number, ts: 0, type: 1, data_type: 0 })
    loading.value = true
    let url = info.api_url + '/api/dtu_get_data?dtu_number=' + dtu_info.dtu_number
    request.get(url).then(res => {
        loading.value = false
        if (res.code === 0) {
            console.log("dtu_get_data", res);
        } else {
            ElMessage.error(res.message)
        }
    }).catch(err => {
        console.log(err);
        loading.value = false
    })
}
const dtu_set_resend = () => {
    if (!dtu_info.dtu_number) {
        ElMessage.warning("请选择dtu设备")
        return
    }
    if (loading.value === true) {
        return
    }
    arrayPush({ content: "设置补发功能 " + dtu_info.dtu_number, ts: 0, type: 1, data_type: 0 })
    loading.value = true
    let url = info.api_url + '/api/dtu_set_resend?dtu_number=' + dtu_info.dtu_number
    request.get(url).then(res => {
        loading.value = false
        if (res.code === 0) {
            console.log("dtu_set_resend", res);
        } else {
            ElMessage.error(res.message)
        }
    }).catch(err => {
        console.log(err);
        loading.value = false
    })
}
const dtu_cancel_resend = () => {
    if (!dtu_info.dtu_number) {
        ElMessage.warning("请选择dtu设备")
        return
    }
    if (loading.value === true) {
        return
    }
    arrayPush({ content: "取消补发功能 " + dtu_info.dtu_number, ts: 0, type: 1, data_type: 0 })
    loading.value = true
    let url = info.api_url + '/api/dtu_cancel_resend?dtu_number=' + dtu_info.dtu_number
    request.get(url).then(res => {
        loading.value = false
        if (res.code === 0) {
            console.log("dtu_cancel_resend", res);
        } else {
            ElMessage.error(res.message)
        }
    }).catch(err => {
        console.log(err);
        loading.value = false
    })
}
const dtu_clear_resend_data = () => {
    if (!dtu_info.dtu_number) {
        ElMessage.warning("请选择dtu设备")
        return
    }
    if (loading.value === true) {
        return
    }
    arrayPush({ content: "清除补发数据 " + dtu_info.dtu_number, ts: 0, type: 1, data_type: 0 })
    loading.value = true
    let url = info.api_url + '/api/dtu_clear_resend_data?dtu_number=' + dtu_info.dtu_number
    request.get(url).then(res => {
        loading.value = false
        if (res.code === 0) {
            console.log("dtu_clear_resend_data", res);
        } else {
            ElMessage.error(res.message)
        }
    }).catch(err => {
        console.log(err);
        loading.value = false
    })
}
const dtu_clear_outage_data = () => {
    if (!dtu_info.dtu_number) {
        ElMessage.warning("请选择dtu设备")
        return
    }
    if (loading.value === true) {
        return
    }
    arrayPush({ content: "清除断电记录 " + dtu_info.dtu_number, ts: 0, type: 1, data_type: 0 })
    loading.value = true
    let url = info.api_url + '/api/dtu_clear_outage_data?dtu_number=' + dtu_info.dtu_number
    request.get(url).then(res => {
        loading.value = false
        if (res.code === 0) {
            console.log("dtu_clear_outage_data", res);
        } else {
            ElMessage.error(res.message)
        }
    }).catch(err => {
        console.log(err);
        loading.value = false
    })
}
const reset_rtu = () => {
    if (!dtu_info.dtu_number) {
        ElMessage.warning("请选择dtu设备")
        return
    }
    if (loading.value === true) {
        return
    }
    arrayPush({ content: "中心复位RTU " + dtu_info.dtu_number, ts: 0, type: 1, data_type: 0 })
    loading.value = true
    let url = info.api_url + '/api/reset_rtu?dtu_number=' + dtu_info.dtu_number
    request.get(url).then(res => {
        loading.value = false
        if (res.code === 0) {
            console.log("reset_rtu", res);
        } else {
            ElMessage.error(res.message)
        }
    }).catch(err => {
        console.log(err);
        loading.value = false
    })
}

const reset_dtu = () => {
    return
    if (!dtu_info.dtu_number) {
        ElMessage.warning("请选择dtu设备")
        return
    }
    if (loading.value === true) {
        return
    }
    arrayPush({ content: "DTU远程复位 " + dtu_info.dtu_number, ts: 0, type: 1, data_type: 0 })
    loading.value = true
    let url = info.api_url + '/api/reset_dtu?dtu_number=' + dtu_info.dtu_number
    request.get(url).then(res => {
        loading.value = false
        if (res.code === 0) {
            console.log("reset_dtu", res);
        } else {
            ElMessage.error(res.message)
        }
    }).catch(err => {
        console.log(err);
        loading.value = false
    })
}

const rtu_get_info = () => {
    if (!dtu_info.dtu_number) {
        ElMessage.warning("请选择dtu设备")
        return
    }
    if (loading.value === true) {
        return
    }
    arrayPush({ content: "查询RTU的参数和状态 " + dtu_info.dtu_number, ts: 0, type: 1, data_type: 0 })
    loading.value = true
    let url = info.api_url + '/api/rtu_get_info?dtu_number=' + dtu_info.dtu_number
    request.get(url).then(res => {
        loading.value = false
        if (res.code === 0) {
            console.log("rtu_get_info", res);
        } else {
            ElMessage.error(res.message)
        }
    }).catch(err => {
        console.log(err);
        loading.value = false
    })
}

const dtu_set_setting = (type) => {
    console.log("dtu_set_setting", type);
    ElMessage.warning("开发中")
    return
    if (!dtu_info.dtu_number) {
        ElMessage.warning("请选择dtu设备")
        return
    }
    if (loading.value === true) {
        return
    }
    }

const dtu_get_setting = () => {
    ElMessage.warning("开发中")
    return
    if (!dtu_info.dtu_number) {
        ElMessage.warning("请选择dtu设备")
        return
    }
    if (loading.value === true) {
        return
    }
    arrayPush({ content: "DTU参数查询 " + dtu_info.dtu_number, ts: 0, type: 1, data_type: 0 })
    loading.value = true
    let url = info.api_url + '/api/dtu_get_setting?dtu_number=' + dtu_info.dtu_number
    request.get(url).then(res => {
        loading.value = false
        if (res.code === 0) {
            console.log("dtu_get_setting", res);
        } else {
            ElMessage.error(res.message)
        }
    }).catch(err => {
        console.log(err);
        loading.value = false
    })
}

const client_list = ref([])
const udp_client_list = () => {
    console.log("显示设置: ",query);
    
    client_list.value = []
    let url = info.api_url + '/api/udp_client_list'
    request.get(url).then(res => {
        if (res.code === 0) {
            // console.log("udp_client_list",res.data.list);
            let keys = Object.keys(res.data.list)
            client_list.value = keys
            if (client_list.value.length > 0) {
                dtu_info.dtu_number = client_list.value[0]
            }
            arrayPush({ content: "获取在线设备 " + keys.length + " 个", ts: 0, type: 1, data_type: 0 })

        } else {
            ElMessage.error(res.message)
        }
    }).catch(err => {
        console.log(err);
    })
}

const consolePanel = ref(null)
const messageList = ref([])

const sendData = () => {
    if (query.data.trim() === '') {
        return
    }
    arrayPush({ content: query.data, ts: 0, type: 1, data_type: 0 })
}

const clearScreen = () => {
    messageList.value = []
    scrollInit()
}

const arrayPush = (obj) => {
    while (messageList.value.length > 300) { // 这里只保存最近的300条信息, 再多就变卡了
        messageList.value.shift()
    }
    obj.ts = Methods.formatDate((new Date()).getTime() / 1000, 'hh:mm:ss')
    messageList.value.push(obj)
    scrollInit()
}
const connectWebSocket = () => {
    reconnecting = true
    socket = new WebSocket(info.ws_url + "/echo");
    socket.onopen = function (res) {
        loginStatus = true
        reconnecting = false; // 重置重连状态
        info.ws_connect_status = "连接成功"
        reconnectAttempts = 0; // 重置重连计数
        // socket.send('tom');
        // let timer = setInterval(function () {
        //     if(loginStatus === false) {
        //         console.log("清除定时器!")
        //         clearInterval(timer)
        //     }
        //     socket.send('tom ' + (new Date()).getTime().toString());
        // },1000)
    }

    socket.onclose = function (e) {
        loginStatus = false
        reconnecting = false
        info.ws_connect_status = "连接断开"
        if (reconnectAttempts < maxReconnectAttempts) {
            attemptReconnect();
        }
    }

    socket.onerror = function (err) {
        info.ws_connect_status = err
    }

    socket.onmessage = function (e) {
        let obj = JSON.parse(e.data)
        console.log("obj",obj);
        
        if (
            query.t0_show && obj.data_type === 0 ||
            query.t1_show && obj.data_type === 1 ||
            query.t2_show && obj.data_type === 2 ||
            query.t3_show && obj.data_type === 3 ||
            query.t4_show && obj.data_type === 4 || obj.data_type === 5
        ) {
            arrayPush({
                content: obj.content, // 消息内容
                ts: 0, // 消息时间
                type: 2, // 1.发送 2.接收
                data_type: obj.data_type
            })
        }
    };
}
const attemptReconnect = () => {
    if (reconnecting) return;
    reconnecting = true;
    info.ws_connect_status = "正在重连..."
    setTimeout(() => {
        reconnectAttempts++;
        connectWebSocket();
    }, reconnectInterval);
}
const scrollInit = () => {
    if (query.auto_scroll) {
        nextTick(() => {
            consolePanel.value.scrollTop = consolePanel.value.scrollHeight
        })
    }
}

const apiTest = () => {
    request.post(info.api_url + '/api/ping', {}).then(res => {
        if (res.data === "pong") {
            info.api_connect_status = "连接成功"
        } else {
            info.api_connect_status = "连接失败"
        }
    }).catch(err => {
        console.log(err);
    })
}
onDeactivated(() => {
    console.log('printer onDeactivated')
})
onUnmounted(() => {
    console.log('printer onUnmounted')
})

// 接收来自主进程的数据
ipcRenderer.on('response-cmd-args', (event, arg) => {
    info.api_url = arg.api_url
    info.ws_url = arg.ws_url
    info.udp_port = arg.udp_port
    console.log(info);
    document.title = "地热数据采集-控制面板 " + info.udp_port// todo 动态修改标题
    apiTest()
    connectWebSocket();
});

onMounted(() => {
    // info.ws_url = window.myAPI.getWSUrl()
    // info.api_url = window.myAPI.getAPIUrl()
    // 向主进程发送请求数据的消息
    ipcRenderer.send('request-cmd-args', '我要获取命令行参数');
    scrollInit()
})
</script>

<style scoped lang="scss">
.custom-container {
    background-color: #efefef;
    width: 100%;
    height: 100%;
    font-size: 14px;
}

.monitor-box {
    width: 100%;
    height: 350px;
    display: flex;
    flex-wrap: nowrap;
}

.control-box {
    height: calc(100% - 350px);
    background-color: #fff;
    font-size: 14px;
}

.monitor-box .console-box {
    height: 100%;
    width: 100%;
    flex-shrink: 0;
    box-sizing: border-box;
    padding: 8px;
}

.console-panel {
    width: 100%;
    height: 100%;
    //border: 1px solid rgba(100,100,100,1);
    background-color: #121212;
    color: #00ff00;
    box-sizing: border-box;
    padding: 10px;
    font-size: 13px;
    line-height: 20px;
    overflow: auto;
    //font-weight: bold;
}

.message-box {
    display: flex;
    flex-wrap: nowrap;
    align-content: center;
}

.message-box .message-time {
    display: inline-block;
    width: 120px;
}

.message-box .message-item {
    flex: 1;
    word-break: break-all;
}

// .btn-box {
//   border-radius: 3px;
// }

.btn-bg {
    width: 100%;
    display: flex;
    // padding: 10px 0;
    box-sizing: border-box;
    background-color: #ffffff;
}

.form-row {
    display: flex;
    flex-wrap: nowrap;
    align-items: center;
    padding: 8px;
}

.form-row .row-label {
    // width: 80px;
    color: #595959;
    text-align: right;
    padding-right: 5px;
}

.page2 {
    display: flex;
}
.page2 .left {
    width:260px;
    flex-shrink: 0;
}
.page2 .right {
    flex: 1;
}
.page2 .left .form-row {
    padding: 3px;
}
.page2 .left .form-row .row-label {
    width: 70px;
}



.form-row .row-value {
    flex: 1;
}

::v-deep(.tab-container .el-tabs__item) {
    // background-color: #00ff00;
    padding: 0 10px !important;
    line-height: 30px;
    height: 30px;
    font-size: 12px;
}

::v-deep(.tab-container .el-tabs__header) {
    margin: 0;
}
</style>
